﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading;
using System.Timers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; 
using Newtonsoft.Json; 
using CarparkIMS_Model; 
using Microsoft.Extensions.Options;
using System.Threading.Tasks;

namespace CarparkBusiness
{
    partial class Program
    {
        static int needToClearCount = 0;
        public static async Task Main(string[] args)
        {
            Console.Clear();
            Loading.RenderProgress(); 
            Console.WriteLine("ENTER TO TASKS.....");
            Console.WriteLine("SPACE BAR TO RUN ONCE.....");
            DateTime sysBootDateTime = DateTime.Now; 
            ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();

            var services = new ServiceCollection();
            TaskStartUp.ConfigureServices(services);
            var serviceProvider = services.BuildServiceProvider();
            ParkingSetting parkingSetting = serviceProvider.GetService<IOptions<ParkingSetting>>().Value;
#if DEBUG
            while (consoleKeyInfo.Key == ConsoleKey.Spacebar)
            { 
                if (consoleKeyInfo.Key != ConsoleKey.Enter)
                { 
                    await serviceProvider.GetService<MainCalcControlLer>().Run(args);
                }

                if (consoleKeyInfo.Key == ConsoleKey.Enter)
                    break;

                Console.WriteLine("--------------------------------------------------------------------------");
                Console.WriteLine("SPACE BAR TO RUN ONCE.....");
                Console.WriteLine("ENTER TO JOB TASKS.....");

                consoleKeyInfo = Console.ReadKey();
            }
#endif
            //====================================================================================================
            Console.Title = string.Format("TASK RUNNING PLAN [PARKING PLACE STATISTICS] [{0}]", Environment.CurrentDirectory);
            var watch = new Stopwatch();
             
            Console.WriteLine("[CarParkingScheduleTask.RunTask].....");
            await CarParkingScheduleTask.RunTask(args, parkingSetting.IntervalMinutes);
            //=============================================================================================================================================

            watch.Stop();
            var time = watch.ElapsedMilliseconds;
            Console.WriteLine($"Elapsed Time:{time} ms");
            Thread.SpinWait(10000);

            //HEART BEAN ---------------------------------------------------------
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.AutoReset = true;
            timer.Interval = 60000;
            timer.Elapsed += new ElapsedEventHandler(Tick);
            timer.Start();

            #region QUIT  
            Loading.InputBusiness(out string quitInputChar, "QC", "\nPress Q to quit...");
            #endregion

            //Console.ReadKey(); 
        }
        public static void Tick(object sender, System.Timers.ElapsedEventArgs e)
        {
            if(needToClearCount > 600)
            {
                Console.Clear();
            }

            string log1 = string.Format(" [SYSTEM IS RUNNING {0:yyyy-MM-dd HH:mm:ss fff}]", DateTime.Now); 
            Console.WriteLine($"\n{log1}\n"); 
            
            needToClearCount++;
        }
    }
    
    public class TaskStartUp
    {
        public static void ConfigureServices(IServiceCollection services)
        { 
            var Configuration = ReadFromAppSettings();
            services.AddDbContextPool<IMSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("IMSDatabase")));
            var serviceProvider = services.BuildServiceProvider();
            services.AddTransient<MainCalcControlLer>();
            services.Configure<ParkingSetting>(Configuration.GetSection("parkingSetting"));
            services.AddLogging(builder =>
            {
               // builder.ClearProviders();
                builder.AddConsole();
                builder.AddDebug();
            }) ; 
        }

        public static IConfigurationRoot ReadFromAppSettings()
        {
            return new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT")}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();
        }
    }
}
